import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;

public class TestJSON {
    public static void main(String[] args) throws IOException
    {


        // json格式String ->   对象

        // fastjson.jar

        // 主要的类:
        // JSONObject
        // JSONArray

        // 1. String -> JSON对象
//		String bookStr = readFile("book.json");
//		System.out.println(bookStr);
//		JSONObject jsonObj1 = JSONObject.parseObject(bookStr);
//		System.out.println(jsonObj1.getString("id"));
//		System.out.println(jsonObj1.getString("name"));
//		System.out.println(jsonObj1.getString("author"));
//		System.out.println(jsonObj1.getString("year"));

        // 2. String -> JSON数组
//		String booksStr = readFile("books.json");
//		System.out.println(booksStr);
//		JSONArray jsonArr = JSONArray.parseArray(booksStr);
//		for(int i=0;i<jsonArr.size();i++)
//		{
//			JSONObject j = jsonArr.getJSONObject(i);
//			System.out.println(j.getString("id"));
//			System.out.println(j.getString("name"));
//			System.out.println(j.getString("author"));
//			System.out.println(j.getString("year"));
//		}

        // 3. String -> JSON对象
//		String bookstoreStr = readFile("bookstore.json");
//		JSONObject j1 = JSONObject.parseObject(bookstoreStr);
//		System.out.println(j1);
//		System.out.println(j1.getString("name"));
//		System.out.println(j1.getString("address"));
//		JSONArray j2 = j1.getJSONArray("books");
//		for(int i=0;i<j2.size();i++)
//		{
//			JSONObject j3 = j2.getJSONObject(i);
//			System.out.println(j3.getString("id"));
//			System.out.println(j3.getString("name"));
//			System.out.println(j3.getString("author"));
//			System.out.println(j3.getString("year"));
//		}




        // 3. String -> JSON对象
		String bookstoreStr = readFile("D:\\03chenhaisheng_jspservlet\\JavaEE\\_11JSON\\class1.json");
		JSONObject j1 = JSONObject.parseObject(bookstoreStr);
		System.out.println(j1);
		System.out.println(j1.getString("classname"));
		System.out.println(j1.getString("teacher"));
		JSONArray j2 = j1.getJSONArray("students");
		for(int i=0;i<j2.size();i++)
		{
			JSONObject j3 = j2.getJSONObject(i);
			System.out.println(j3.getString("id"));
			System.out.println(j3.getString("name"));
			System.out.println(j3.getString("age"));
		}


    }

    public static String readFile(String filePath) throws IOException, FileNotFoundException {
        // 1. 打开文件
        Reader r = new FileReader(filePath);

        // 2. 读取数据
        int len = 0;
        char[] buf = new char[1024];
        StringBuilder sb = new StringBuilder();
        while((len=r.read(buf))!=-1)
        {
            sb.append(buf,0,len);
        }

        // 3. 关闭文件
        r.close();

        return sb.toString();
    }

}

